const router = require("koa-router")();
const ShopcarModel = require("../../models/shopcar")
// const uploa d = require("../../config/multer")        //不需要了
const path = require("path");               //加
// const fs = require("fs")    //使用这个模块实现文件的读写    //utils/upload.js
const fileUpload = require("../../utils/upload")
// router.post('/m1/doAdd',upload.single('file'), async (ctx, next) => {
router.post('/m1/doAdd',async ctx=> {
    console.log(ctx.request.body)
    var {name,singer,like,playCount} = ctx.request.body;
    var file = ctx.request.files.file;
    // console.log(file)//a lot
    // console.log(Boolean(file.name.trim()))//true
    var uploadName = path.basename(file.path)
    // console.log(uploadName)
    var isUpload = Boolean(file.name.trim());
    var data ={name,singer,like:Boolean(like),playCount};
    if(isUpload){
        fileUpload(file.path,uploadName);
        // console.log(uploadName)
        // console.log(ctx.origin)//localhost:8082
        var imgUrl = ctx.origin +"/"+uploadName;
        console.log(imgUrl)
        data.imgUrl = imgUrl;
    }
    var db = new ShopcarModel(data)
    db.save(err => {
        if (err) {
            throw err
        };
    })
    ctx.redirect("/m1")
    /* //将本地图片放到服务器的static文件夹中
    // 创建可读流
    const reader = fs.createReadStream(file.path);
    // 获取上传文件扩展名
    let filePath = process.cwd() + `/static/${uploadname}`;
    // 创建可写流
    const upStream = fs.createWriteStream(filePath);
    // 可读流通过管道写入可写流
    reader.pipe(upStream); */       //utils/upload.js
}) 
module.exports = router;